﻿using System;
using System.Linq;
using System.Web.Mvc;
using Grundy.Administration.Web.Services;
using Grundy.Common;

namespace Grundy.Administration.Web.Controllers
{
    [Authorize]
    public class CustomerController : Controller
    {
        private CustomerService _customerService;
        private readonly Application _application;

        public CustomerController()
        {
            _application = Application.Instance;
            _customerService = new CustomerService(_application.ServerCryptographicServicesProvider);
        }

        public CustomerController(CustomerService CustomerService, Application application)
        {
            _customerService = CustomerService;
            _application = application;
        }

        [HttpPost]
        public ActionResult GetCustomersData(int page = 1, int rows = 0)
        {
            var totalRecords = _customerService.GetCustomers().Count();
            var customers = _customerService.GetCustomers(page, rows)
                           .Select(i => new { i.Id, i.Name })
                           .ToList();

            var data = new
            {
                total = page,
                page = page,
                records = totalRecords,
                rows = customers.Select((i) => new { Id = i.Id, cell = new object[] { i.Id, i.Name } }).ToList()
            };

            return Json(data);
        }

        public ActionResult GetCustomers()
        {
            var totalRecords = _customerService.GetCustomers().Count();
            ViewBag.IsEmpty = totalRecords == 0;
            return View();
        }

        [HttpPost]
        public ActionResult New(string name)
        {
            var customer = _customerService.GetCustomer(name);
            if (customer == null)
            {
                var created = _customerService.CreateCustomer(name.Trim());
                return Json(new object[] { true, string.Empty, created.Id });
            }
            return Json(new object[] { false, "A customer with the same name already exists.", Guid.Empty });
        }

        public ActionResult SearchCustomers(string term)
        {  
            if (term.IsNullOrEmpty() || term.Length < 2)
                return Json(new object[] { }, JsonRequestBehavior.AllowGet);

            var matching = _customerService.GetCustomers().Where(i => i.Name.StartsWith(term))
                           .Select(i => i.Name)
                           .ToList();
            return Json(matching, JsonRequestBehavior.AllowGet);
        }
    }
}